﻿Public Class MqParamForm 

    ''' <summary>
    ''' Queryname of the MetaQuery to read
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property QueryName As String


    Public Property SelectedParamText() As String()



    Public Property LastQueryName As String
    ''' <summary>
    ''' Datatable use to input all parameter value
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property ParamTable As DataTable
    ''' <summary>
    ''' Values that user have intput, so we can use it for our Report or Pivot etc...
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property SelectedParam As DataRow
    ''' <summary>
    ''' Metacommand associate with the Queryname
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property MetaCommand As MetaQuery

    Private Property today As DateTime

    Private WithEvents editorRow As EditorRow
    Private WithEvents timeEdit As RepositoryItemTimeEdit
    Private calcEdit As RepositoryItemCalcEdit
    'Private MemoEdit As RepositoryItemMemoEdit
    'Private RichTextEdit As RepositoryItemRichTextEdit
    Private formatType As DevExpress.Utils.FormatType

    Public Sub New()
        ' This call is required by the designer.
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call.
        timeEdit = New RepositoryItemTimeEdit()
        calcEdit = New RepositoryItemCalcEdit()
        today = DateTime.Now
    End Sub

    Public Sub New(ByVal queryName As String)
        Me.New()
        Me.QueryName = queryName
    End Sub

    Private Sub MqParamForm_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        Try
            Me.Cursor = Cursors.WaitCursor
            If Not QueryName = LastQueryName Then

                LastQueryName = QueryName

                Me.Focus()
                Me.Refresh()
                Me.VGridControl1.BeginUpdate()
                InitFormData()
                InitView()
                Me.VGridControl1.EndUpdate()
                Me.Refresh()
                '
                Me.VGridControl1.BeginUpdate()
                MetaCommand.GetParamsLOV_LKP()
                AssignLOV()
                ReDim SelectedParamText(VGridControl1.Rows.Count - 1)
                Me.VGridControl1.EndUpdate()
                Me.Refresh()
            End If

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            MessageWindow.ShowMessage(ex, MsgBoxStyle.Information)
        End Try
    End Sub

    ''' <summary>
    ''' Construct the data table to get parameters
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub InitFormData()
        Dim column As DataColumn = Nothing
        MetaCommand = MetaQuery.GetMetaQueryByName(QueryName)
        If MetaCommand IsNot Nothing Then

            Me.Text = MetaCommand.Caption
            ParamTable = New DataTable(MetaCommand.QueryName)
            For Each row As DataRow In MetaCommand.MetaParams.Rows
                column = ParamTable.Columns.Add()
                column.ColumnName = row("ColumnName").ToString
                column.Caption = row("pCaption").ToString
                column.SetOrdinal(CInt(row("pOrder")))
                column.DataType = IdRepository.GUIDToType(CType(row("pDataTypeID_FK"), Guid))
            Next

            SelectedParam = ParamTable.NewRow
            ParamTable.Rows.Add(SelectedParam)
            VGridControl1.DataSource = ParamTable
            VGridControl1.RetrieveFields()
        Else
            Throw New Exception(String.Format("Invalid Parameter MetaCommand{0}{0}{1}", vbCrLf, QueryName))
        End If
    End Sub

    Public Sub InitView()
        Dim baseRow As BaseRow
        Dim colVisible As Integer
        Dim colname As String
        Dim columnIsVisible As Boolean

        For Each row As DataRow In MetaCommand.MetaParams.Rows
            'Vgrid add row prefix to their name
            colname = String.Format("row{0}", row("ColumnName"))


            'OutStandingIssue: BUG DevExpress 12.2.5, Qq'part ils remplacent les @ par des _ / AL - 2013-01-16
            Dim rowBugName As String = colname
            rowBugName = rowBugName.Replace("@", "_")
            baseRow = VGridControl1.Rows(rowBugName)
            If baseRow IsNot Nothing Then
                editorRow = TryCast(baseRow, EditorRow)
                colVisible = CInt(row("pVisible"))
                Select Case colVisible
                    Case 0 'On cache la colonne
                        columnIsVisible = False
                    Case 1 'On affiche la colonne
                        columnIsVisible = True
                    Case 2 'On affiche la colonne selon le profile du user
                        columnIsVisible = False
                        If AppManager.ApplicationOption.DescriptionColumnIndex = 3 Then   'L'usager a choisi ALT
                            If colname.EndsWith("_ALT") Then
                                columnIsVisible = True
                            End If
                        Else 'L'usager a choisi PRM
                            If colname.EndsWith("_PRM") Then
                                columnIsVisible = True
                            End If
                        End If
                    Case Else
                        columnIsVisible = False
                End Select
                editorRow.Visible = columnIsVisible
                editorRow.Enabled = Not CBool(row("pLocked"))
                editorRow.OptionsRow.ShowInCustomizationForm = True
                editorRow.Properties.ToolTip = row("pToolTip").ToString
                If Not String.IsNullOrEmpty(Trim(row("pBackColor").ToString)) Then
                    editorRow.Appearance.BackColor = ColorTranslator.FromOle(Math.Abs(CInt(row("pBackColor"))))
                End If

                formatType = DevExGridHelper.GetFormatType(row)
                If formatType = DevExpress.Utils.FormatType.DateTime Then
                    timeEdit.DisplayFormat.FormatType = formatType
                    timeEdit.DisplayFormat.FormatString = row("pNumberFormat").ToString
                    timeEdit.EditFormat.FormatType = formatType
                    timeEdit.EditFormat.FormatString = row("pNumberFormat").ToString
                    timeEdit.EditMask = row("pNumberFormat").ToString
                    timeEdit.Mask.AutoComplete = Mask.AutoCompleteType.None
                    timeEdit.AllowNullInput = DevExpress.Utils.DefaultBoolean.False
                    timeEdit.AllowMouseWheel = True
                    editorRow.Properties.RowEdit = timeEdit
                End If
                '
                If formatType = DevExpress.Utils.FormatType.Numeric Then
                    calcEdit.EditFormat.FormatType = DevExpress.Utils.FormatType.Numeric
                    calcEdit.EditFormat.FormatString = row("pNumberFormat").ToString()
                    calcEdit.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric
                    calcEdit.DisplayFormat.FormatString = row("pNumberFormat").ToString()
                    editorRow.Properties.RowEdit = calcEdit
                End If

                'If Not IsDBNull(row("pNumberFormatID_FK")) Then
                '    If CType(row("pNumberFormatID_FK"), Guid) = IdRepository.META_NUMBERFORMAT_EXTERNALEDITOR Then
                '        Select Case row("pNumberFormat").ToString
                '            Case "RichText"
                '                EditorRow.Properties.RowEdit = RichTextEdit
                '            Case ("Memo")
                '                EditorRow.Properties.RowEdit = MemoEdit
                '            Case Else
                '        End Select
                '    End If
                'End If
                '
                If editorRow.Properties.RowEdit IsNot Nothing Then
                    editorRow.Properties.RowEdit.DisplayFormat.FormatType = formatType
                    editorRow.Properties.RowEdit.DisplayFormat.FormatString = row("pNumberFormat").ToString
                End If
            End If
        Next
        VGridControl1.FocusedRecordCellIndex = 0
        VGridControl1.Tag = MetaCommand.QueryName
    End Sub

    Public Sub AssignLOV()
        Dim aMetaquery As MetaQuery
        Dim colVisible As Boolean
        Dim view As Views.Base.ColumnView '= aLOV.View
        Dim Column As DevExpress.XtraGrid.Columns.GridColumn
        Dim aLOV As RepositoryItemSearchLookUpEdit
        Dim formatType As DevExpress.Utils.FormatType

        Dim hideCol As Boolean
        Dim colname As String

        For Each lookup As KeyValuePair(Of String, Guid) In Me.MetaCommand.ListOfLov
            'testPoint: Verify the GuidField in metaquery , The Guidfield is CASE sensitive, IE: ListvalueID is not equal to ListValueId
            'testPoint: LOV Query Must have the first 4 field Like GUID, Code, Desc_PRM, Desc_ALT in the SELECT Statement


            aMetaquery = CommonExt.MetaQuery.GetMetaQueryById(lookup.Value)
            aMetaquery.FillResultQuery()

            aLOV = New RepositoryItemSearchLookUpEdit() With {.DataSource = aMetaquery.ResultQuery, .DisplayMember = aMetaquery.ResultQuery.Columns(CommonExt.Base.AppManager.ApplicationOption.DescriptionColumnIndex).ToString, .ValueMember = aMetaquery.GUIDField, .PopupFormSize = New Size(800, 300), .NullText = "(none)"}

            aLOV.View.HorzScrollVisibility = Views.Base.ScrollVisibility.Always
            aLOV.View.OptionsView.ColumnAutoWidth = False
            aLOV.View.OptionsView.ShowAutoFilterRow = True
            aLOV.View.OptionsBehavior.ReadOnly = True
            view = aLOV.View
            view.Columns.Clear()
            For Each row As DataRow In aMetaquery.MetaColumns.Rows
                colname = row("ColumnName").ToString
                hideCol = False
                If AppManager.ApplicationOption.DescriptionColumnIndex = 2 Then
                    If colname.EndsWith("_ALT") Then
                        hideCol = True
                    End If
                Else
                    If colname.EndsWith("_PRM") Then
                        hideCol = True
                    End If
                End If
                If hideCol = False Then
                    'LOV a pas de Column Chosser donc on affiche juste les 1
                    If CInt(row("pVisible")) = 3 Or CInt(row("pVisible")) = 0 Then
                        colVisible = False
                    Else
                        colVisible = True
                    End If
                    Column = view.Columns.AddField(colname)
                    Column.VisibleIndex = CInt(row("pOrder"))
                    Column.Caption = row("pCaption").ToString
                    Column.Visible = colVisible
                    Column.Width = CInt(row("pWidth"))
                    Column.ToolTip = row("pToolTip").ToString

                    formatType = DevExGridHelper.GetFormatType(row)
                    '
                    Column.DisplayFormat.FormatType = formatType
                    Column.DisplayFormat.FormatString = row("pNumberFormat").ToString
                End If
            Next
            ' bug de memoire
            'http://www.devexpress.com/Support/Center/p/B147229.aspx?searchtext=memory+leak&p=T4|P1|0
            VGridControl1.RepositoryItems.Add(aLOV)
            ' fin 

            'OutStandingIssue: BUG DevExpress 12.2.5, Qq'part ils remplacent les @ par des _ / AL - 2013-01-16
            Dim rowBugName As String = "row" + lookup.Key
            rowBugName = rowBugName.Replace("@", "_")
            VGridControl1.Rows(rowBugName).Properties.RowEdit = aLOV
            aMetaquery.Dispose()
            'View.Dispose()
        Next
    End Sub

    Private Sub MqParamForm_FormClosed(sender As System.Object, e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed

        'Me.Dispose()
    End Sub

    Private Sub btnPrint_Click(sender As System.Object, e As System.EventArgs) Handles btnOK.Click
        SelectedParam = ParamTable.Rows(0)

    End Sub

    Private Sub btnCancel_Click(sender As System.Object, e As System.EventArgs) Handles btnCancel.Click
        SelectedParam = Nothing
        SelectedParamText = Nothing
        Me.DialogResult = Windows.Forms.DialogResult.Cancel
    End Sub

    Private Sub VGridControl1_CellValueChanged(sender As Object, e As DevExpress.XtraVerticalGrid.Events.CellValueChangedEventArgs) Handles VGridControl1.CellValueChanged



        If TypeOf e.Row.Properties.RowEdit Is RepositoryItemSearchLookUpEdit Then
            SelectedParamText(e.RecordIndex) = TryCast(e.Row.Properties.RowEdit, RepositoryItemSearchLookUpEdit).GetDisplayText(e.Value)
        Else
            SelectedParamText(e.RecordIndex) = e.Value.ToString
        End If





    End Sub


    Private Sub VGridControl1_KeyUp(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles VGridControl1.KeyUp
        Dim message As String

        If e.Control AndAlso e.Alt AndAlso e.KeyCode = Keys.Q Then
            message = String.Concat("MetaQuery: ", MetaCommand.QueryName, vbCrLf)
            MessageWindow.ShowMessage(Message, MsgBoxStyle.Information)
            e.Handled = True 'TestPoint: Si on le met pas on peut passer 2 ou 3 fois selon le nombre de touche. aleblanc
        End If
    End Sub




    Private Sub VGridControl1_ShownEditor(sender As Object, e As EventArgs) Handles VGridControl1.ShownEditor
        If TypeOf Me.VGridControl1.ActiveEditor Is TimeEdit Then
            If IsDBNull(Me.VGridControl1.ActiveEditor.EditValue) Then
                Me.VGridControl1.ActiveEditor.EditValue = today
            End If
        End If
    End Sub

    Private Sub timeEdit_FormatEditValue(sender As Object, e As DevExpress.XtraEditors.Controls.ConvertEditValueEventArgs) Handles timeEdit.FormatEditValue
        If IsDBNull(e.Value) Then
            e.Value = today
        End If
    End Sub


End Class